package org.huaiyan.oauth.uaa.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.huaiyan.oauth.uaa.dao.pojo.TabAdminUser;
import org.huaiyan.oauth.uaa.dao.mapper.TabAdminUserMapper;
import org.huaiyan.oauth.uaa.dao.pojo.TabRole;
import org.huaiyan.oauth.uaa.dao.pojo.TabUser;
import org.huaiyan.oauth.uaa.services.TabAdminUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * <p>
 * 后台用户表 服务实现类
 *
 * @author huaiyan
 * @EnableWebSecurity 标识启用webSecurity
 * </p>
 * @since 2021-10-18
 */
@Service
@EnableWebSecurity
public class TabAdminUserServiceImpl extends ServiceImpl<TabAdminUserMapper, TabAdminUser> implements TabAdminUserService, UserDetailsService {


    @Autowired
    private TabAdminUserMapper tabAdminUserMapper;

    /**
     * 根据用户名查询数据
     *
     * @param username 用户名
     * @return org.springframework.security.core.userdetails
     * @date 2021/10/18 15:40
     * @author huaiyan
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TabUser tabUser = tabAdminUserMapper.findUserByUsername(username);
        Optional.ofNullable(tabUser).orElseThrow(() -> new UsernameNotFoundException("用户名或密码不正确"));
        setRoleList(tabUser);
        return tabUser;
    }

    /**
     * 根据用户查询用户具备那些角色
     *
     * @param user 用户
     * @return
     * @date 2021/10/19 10:56
     * @author huaiyan
     */
    private void setRoleList(TabUser user) {
        List<TabRole> list = this.tabAdminUserMapper.selectRolesByUserId(user.getUserId());
        user.setRoles(list);
    }
}
